<?php

use models\Business\Member;
use models\DAO\OrderModel;
use models\Exception\Business\AlibabaproductException;
use models\Service\AlibabaproductService;
use Yaf\Registry;
use models\Business\Alibaba;
use Task\client;
use models\Business\AlibabaProduct;
use models\Business\AlibabaAttribute;
use models\Business\AlibabaSku;
use models\Business\AlibabaShipping;
use models\Business\AlibabaActivity;
use models\Service\AlibabacategoryService;
use models\Service\OrderService;
use models\Business\Order;

class AlibabaController extends ApiBaseController
{
    /**
     * 获取商品分类
     * @throws Exception
     */
    public function getCategoryAction() {
        try {
            // 入库
            $parameters = Registry::get('parameters');
            Registry::get('alibaba_log')->info(__METHOD__ . ' parameters: ' . json_encode($parameters));

            // 97 => 1043171 => 1043183
            $category_list = Alibaba::getSubCategoryById($parameters['category_id']);
            Registry::get('alibaba_log')->info(__METHOD__ . ' response: ' . json_encode($category_list));

            $res = AlibabacategoryService::getInstance()->batchInsert($category_list);
            Registry::get('alibaba_log')->info(__METHOD__ . ' result: ' . json_encode($res));

        } catch (Exception $e) {
            Registry::get('alibaba_log')->err(__METHOD__ . ' error: ' . $e->getMessage());
            throw $e;
        }

    }

    /**
     * 获取商品库列表
     * @throws Exception
     */
    public function listCybUserGroupAction() {
        try {
            $parameters = Registry::get('parameters');
            Registry::get('alibaba_log')->info(__METHOD__ . ' parameters: ' . json_encode($parameters));

            $user_group = Alibaba::getProductListCybUserGroup($parameters['page']);

            if (!empty($user_group)) {
                Registry::get('alibaba_log')->info(__METHOD__ . ' response: ' . json_encode($user_group));

                $page_size = 20;

                $client = new client();
                $client->connect();

                foreach ($user_group['result']['result'] as $group_info) {
                    $total_page = ceil($group_info['feedCount'] / $page_size);
                    Registry::get('alibaba_log')->info(__METHOD__ . ' total_page: ' . $total_page);
                    Registry::get('alibaba_log')->info(__METHOD__ . ' methods: ' . json_encode(get_class_methods($client)));
                    for ($page = 1; $page <= $total_page; $page++) {
                        Registry::get('alibaba_log')->info(__METHOD__ . ' page: ' . $page);
                        Registry::get('alibaba_log')->info(__METHOD__ . ' data: ' . json_encode([$group_info['id'], $page, $page_size]));
                        $client->productListCybUserGroupFeed($group_info['id'], $page, $page_size);
                    }
                }
                $client->close();
            }
            return $this->_responseJson(new stdClass(), '000', __METHOD__ . 'done');
        } catch (Exception $e) {
            Registry::get('alibaba_log')->err(__METHOD__ . ' error: ' . $e->getMessage());
            throw $e;
        }

    }

    /**
     * 获取选品库下商品列表
     * @throws Exception
     */
    public function productListCybUserGroupFeedAction() {
        set_time_limit(300);
        $parameters = Registry::get('parameters');

        Registry::get('alibaba_log')->info(__METHOD__ . ' parameters: ' . json_encode($parameters));
        try {
            $match_product_arr = [];
            $product_list = Alibaba::getProductListCybUserGroupFeed(
                $parameters['group_id'],
                $parameters['page'],
                isset($parameters['page_size']) ? $parameters['page_size'] : 10,
                isset($parameters['feed_id']) ? $parameters['feed_id'] : '',
                isset($parameters['title']) ? $parameters['title'] : '');
            Registry::get('alibaba_log')->info(__METHOD__ . ' response: ' . json_encode($product_list));

            if (!empty($product_list) && empty($product_arr) && empty($match_product_arr)) {
                $product_arr = $product_list;
                $product_id_arr = array_column($product_list, 'product_id');
            }

            if (!empty($product_arr) && ! empty($product_id_arr)) {
                // product数据入库
                AlibabaProduct::collectProduct($product_arr);

                foreach ($product_id_arr as $product_id) {
                    $client = new client();
                    $client->connect();
                    // 查询商品详情
                    $client->productCpsMediaProductInfo($product_id);
                    // 查询营销活动
//                    list($sku_arr, $product_sku_arr, $sale_info_arr, $shipping_arr, $freight_arr, $attribute_arr, $match_sku_id_arr) =
//                        Alibaba::getProductCpsMediaProductInfo($product_info['product_id']);
                    $client->close();
                    sleep(1.0);
                }
            }

        } catch (Exception $e) {
            Registry::get('alibaba_log')->err(__METHOD__ . ' error: ' . $e->getMessage());
            throw $e;
        }
        return $this->_responseJson(new stdClass(), '000', __METHOD__ . 'done');
    }

    /**
     * 查询商品详情
     * @throws Exception
     */
    public function productCpsMediaProductInfoAction() {
        try {
            $parameters = Registry::get('parameters');
            Registry::get('alibaba_log')->info(__METHOD__ . ' parameters: ' . json_encode($parameters));

            // 判断商品是否存在
            AlibabaProduct::getProductByProductId($parameters['product_id']);

            // 商品存在调用接口获取数据
            list($product_arr, $sku_arr, $product_sku_arr, $shipping_arr, $attributes_arr) =
                Alibaba::getProductCpsMediaProductInfo($parameters['product_id']);

            Registry::get('alibaba_log')->info(__METHOD__ . ' response: ' .
                json_encode([$product_arr, $sku_arr, $product_sku_arr, $attributes_arr, $shipping_arr]));

            // 数据获取成功 更新数据
            // 更新attribute数据
            $attribute_value = [];
            if (! empty($sku_arr))
                $attribute_value = AlibabaAttribute::collectAttribute($sku_arr);

            // 更新sku数据
            if (! empty($product_sku_arr)) {
                // 更新sku数据
                foreach ($product_sku_arr as $idx => $sku_info) {
                    $sku_attribute_value_arr = explode(',', $sku_info['attribute_id']);
                    $attribute_id_arr = [];
                    foreach ($sku_attribute_value_arr as $attribute_name) {
                        if (isset($attribute_value[$attribute_name])) {
                            array_push($attribute_id_arr, $attribute_value[$attribute_name]);
                        }
                    }
                    $product_sku_arr[$idx]['attribute_id'] = implode(',', $attribute_id_arr);
                }
                AlibabaSku::collectSku($product_sku_arr);
            }

            // 商品信息不为空，更新数据库
            if (! empty($product_arr)) {
                if (!isset($product_arr))
                    $product_arr['product_id'] = $parameters['product_id'];
                $product_arr['fake_platform_sales'] = mt_rand(98, 1002);
                $into_product_arr = $product_arr;
                $product = AlibabaProduct::getProductByProductId($into_product_arr['product_id']);
//                $product = AlibabaProduct::getProduct(['id' => $into_product_arr['product_id']]);
                $product = $product['data'][0];
                if (isset($product['title']) && ! empty($product['title']))
                    unset($into_product_arr['title']);
                if (isset($product['images']) && ! empty($product['image']))
                    unset($into_product_arr['images']);
                if (isset($product['img_url']) && ! empty($product['img_url']))
                    unset($into_product_arr['img_url']);
                AlibabaProduct::editProduct($into_product_arr);
            }

            if (! empty($shipping_arr)) {
                AlibabaShipping::collectShipping($shipping_arr);
                // sku存在 且 商品主图列表不为空时 商品上线
                if (!empty($sku_arr) && ! empty($product_arr['images']))
                    AlibabaProduct::editProduct(['product_id' => $parameters['product_id'], 'stats' => 1]);
            }
//            if (! empty($freight_arr)) {
//
//            }

            // 关注商品
            $client = new client();
            $client->connect();
            $client->alibabaProductFollowAction($parameters['product_id']);
            $client->close();

            return $this->_responseJson(new stdClass(), '000', __METHOD__ . 'done');
        } catch (Exception $e) {
            Registry::get('alibaba_log')->err(__METHOD__ . ' error: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 查询指定商品参与的促销活动
     * @throws Exception
     */
    public function queryOfferDetailActivityAction() {
        try {
            $parameters = Registry::get('parameters');
            Registry::get('alibaba_log')->info(__METHOD__ . ' parameters: ' . json_encode($parameters));

            list($activity_info, $product_activity_info) = Alibaba::getProductQueryOfferDetailActivity($parameters['product_id']);

            if (!empty($activity_info))
                AlibabaActivity::collectActivity([$activity_info]);

            if (! empty($product_activity_info))
                AlibabaActivity::collectProductActivity($product_activity_info);

            Registry::get('alibaba_log')->info(__METHOD__ . ' response: ' . json_encode([$activity_info, $product_activity_info]));
        } catch (Exception $e) {
            Registry::get('alibaba_log')->err(__METHOD__ . ' error: ' . $e->getMessage());
            throw $e;
        }
        return $this->_responseJson(new stdClass(), '000', __METHOD__ . 'done');
    }

    public function followAction() {
        try {
            $parameters = Registry::get('parameters');
            Registry::get('alibaba_log')->info(__METHOD__ . ' parameters: ' . json_encode($parameters));

            $res = Alibaba::getProductFollow($parameters['product_id']);
            // 商品关注成功后，默认上线
            if ($res !== true)
                AlibabaProduct::editProduct(['product_id' => $parameters['product_id'], 'stats' => 0]);
            Registry::get('alibaba_log')->info(__METHOD__ . ' response: ' . json_encode($res));

            // 查询营销活动
//            $client = new client();
//            $client->connect();
//            $client->queryOfferDetailActivity($parameters['product_id']);
//            $client->close();

//            return $this->_responseString('success');
            return $this->_responseJson(new stdClass(), '000', 'success');
        } catch (Exception $e) {
            Registry::get('alibaba_log')->err(__METHOD__ . ' error: ' . $e->getMessage());
            throw $e;
        }
    }

    public function unfollowAction() {
        try {
            $parameters = Registry::get('parameters');
            Registry::get('alibaba_log')->info(__METHOD__ . ' parameters: ' . json_encode($parameters));

            $res = Alibaba::unFollowProduct($parameters['product_id']);
            Registry::get('alibaba_log')->info(__METHOD__ . ' response: ' . json_encode($res));

            return $this->_responseString('success');
        } catch (Exception $e) {
            Registry::get('alibaba_log')->err(__METHOD__ . ' error: ' . $e->getMessage());
            throw $e;
        }

    }

    public function refundReturnAction() {
        $parameters = Registry::get('parameters');
        try {
            Registry::get('alibaba_log')->info("1688退货退款接口。订单编号(" . $parameters['refund_info']['order_sn'] . ")调用1688退款退货接口参数: " . json_encode([
                    'parameters' => $parameters['refund_info'], 'orders' => $parameters['order_info']]));
            $msg = Order::refundReturn($parameters['refund_info'], $parameters['order_info']);
            // 记录refundReturn的结果
            Registry::get('alibaba_log')->info("1688退货退款接口。订单编号(" . $parameters['refund_info']['order_sn'] . ")调用1688退款退货接口结果: " . $msg);

            return $this->_responseString('success');
        } catch (Exception $e) {
            Registry::get('alibaba_log')->err('1688退货退款接口。error: ' . $e->getMessage());
        }
    }

    /**
     * 自动确认收货
     * @return bool
     * @throws \models\Exception\DAO\ModelSqlException
     * @throws \ylAlibaba\core\ylAlibabaException
     */
    public function getDeliveryBySnAction() {
        $parameters = Registry::get('parameters');
        Registry::get('alibaba_log')->info(__METHOD__ . ' 1688订单编号: ' . json_encode($parameters));
        list($delivery_no, $delivery_no_1688, $company_name, $status) = Alibaba::getDeliveryNo($parameters['sn']);
        Registry::get('alibaba_log')->info(__METHOD__ . ' 1688运单信息: ' . json_encode([$delivery_no, $delivery_no_1688, $company_name, $status]));
        // 已签收，可能在菜鸟驿站，也可能在蜂巢，也可能是用户签收了 修改订单状态为确认收货
        if ($status === 'SIGN') {
            $order_model = OrderModel::getInstance();
            $conn = $order_model->getConn();
            $conn->beginTransaction();
            try {
                $order_info = OrderService::getInstance()->getOne(['groupOp' => 'AND', 'rules' => [
                    ['field' => 'trade_order_sn', 'op' => 'eq', 'data' => $parameters['sn']]]]);
                Registry::get('alibaba_log')->info(__METHOD__ . ' 平台订单订单号: ' . $order_info['sn']);
//                $order_info = OrderService::getInstance()->update(['stats' => 3], $order_info['sn']);
//                Registry::get('alibaba_log')->info(__METHOD__ . ' 平台订单修改结果: ' . json_encode([$order_info]));

                // 修改booking
                $update_booking_sql = "UPDATE `booking` SET `stats` = 6 WHERE `sn` = '" . $order_info['sn'] . "'";
                Registry::get('db_log')->info("修改booing状态sql: " . $update_booking_sql);
                $conn->executeQuery($update_booking_sql);

                $update_order_sql = "UPDATE `order` SET `stats` = 3 WHERE `sn` = '" . $order_info['sn'] . "'";
                $update_balance_sql = $insert_turnover_sql = '';

                //获取商品标题
                $product =  AlibabaproductService::getInstance()->getOne($order_info['product_id']);
                if (empty($product))
                    throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS, AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS_NO);
                // 给拼团失败的用户及其上级、上上级分发金豆
                if (!empty($order_info['fail_member_id']))
                list($update_balance_sql, $insert_turnover_sql) = Member::calCouponFailureMemberIntegral(
                    $order_info['fail_member_id'], $order_info['amount']-$order_info['fee'], $order_info['cost']-$order_info['post_fee'], $order_info['fee'],false,2,$product['title'],$order_info['sn']);

                if (!empty($update_balance_sql))
                    $conn->executeQuery($update_balance_sql);

                if (!empty($insert_turnover_sql))
                    $conn->executeQuery($insert_turnover_sql);

                Registry::get('db_log')->info("修改订单状态sql: " . $update_order_sql);
                $conn->executeQuery($update_order_sql);
                $conn->commit();

                $return = 'success';
            } catch (Exception $e) {
                $conn->rollBack();
                Registry::get('alibaba_log')->info(__METHOD__ . ' 平台订单修改失败: {' . $e->getMessage() . '}');
            } finally {
                $return = 'error';
            }
        } else {
            $return = 'failure';
        }
        return $this->_responseString($return);
    }

    public function cleanDbAction() {
        $sql = "select product_id from alibabaproduct where stats = 0 and created_at = updated_at and title = '0' group by product_id order by created_at desc";
        $res = \models\DAO\AlibabaproductModel::getInstance()->query($sql);

        if (!empty($res)) {
            $product_id_arr = array_column($res, 'product_id');
            Registry::get('alibaba_log')->debug("待删除的商品编号: " . json_encode($product_id_arr));

            foreach ($res as $row => $data) {
                try {
                    $unfollow = Alibaba::unFollowProduct($data['product_id']);
                    Registry::get('alibaba_log')->debug($data['product_id'] . "取关结果: " . json_encode($unfollow));
                } catch (Exception $e) {
                    Registry::get('alibaba_log')->debug($data['product_id'] . "取关失败");
                }
            }

            try {
                $sql = "DELETE FROM `alibabaproduct` WHERE `product_id` in ('" . implode("', '", $product_id_arr) . "')";
                $res = \models\DAO\AlibabaproductModel::getInstance()->query($sql);
                Registry::get('alibaba_log')->debug("商品删除结果: " . json_encode($res));
            } catch (Exception $e) {
                Registry::get('alibaba_log')->debug("商品删除失败: " . $e->getMessage());
            }

            try {
                $sql = "DELETE FROM `alibabasku` WHERE `product_id` in ('" . implode("', '", $product_id_arr) . "')";
                \models\DAO\AlibabaproductModel::getInstance()->query($sql);
                Registry::get('alibaba_log')->debug("sku删除结果: " . json_encode($res));
            } catch (Exception $e) {
                Registry::get('alibaba_log')->debug("sku删除失败: " . $e->getMessage());
            }


            try {
                $sql = "DELETE FROM `alibabashipping` WHERE `product_id` in ('" . implode("', '", $product_id_arr) . "')";
                \models\DAO\AlibabaproductModel::getInstance()->query($sql);
                Registry::get('alibaba_log')->debug("运费模板删除结果: " . json_encode($res));
            } catch (Exception $e) {
                Registry::get('alibaba_log')->debug("运费模板删除失败: " . $e->getMessage());
            }

            try {
                $sql = "DELETE FROM `alibabaproductactivity` WHERE `product_id` in ('" . implode("', '", $product_id_arr) . "')";
                \models\DAO\AlibabaproductModel::getInstance()->query($sql);
                Registry::get('alibaba_log')->debug("活动删除结果: " . json_encode($res));
            } catch (Exception $e) {
                Registry::get('alibaba_log')->debug("活动删除结果失败: " . $e->getMessage());
            }
        }
    }
}
